package com.lagou.edu.source;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.jdbc.datasource.AbstractDataSource;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author 赵虎
 * @date 2020/11/30 12:10
 */
@Component
public class CustomizeHikariDataSource extends AbstractDataSource {

    private static HikariDataSource hikariDataSource;

    @Override
    public Connection getConnection() throws SQLException {
        if(hikariDataSource==null){
            throw new SQLException("未设置数据源");
        }
        return hikariDataSource.getConnection();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        if(hikariDataSource==null){
            throw new SQLException("未设置数据源");
        }
        return hikariDataSource.getConnection(username, password);
    }

    private void destroy(){
        if (hikariDataSource != null) {
            hikariDataSource.close();
        }
    }

    public void setDataSourceMap(HikariDataSource value) {
        destroy();
        hikariDataSource = value;
    }

}
